package com.qiyuesuo.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiyuesuo.domain.MyFile;
import com.qiyuesuo.mapper.FileMapper;
import com.qiyuesuo.service.FileService;
import com.sun.deploy.net.URLEncoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;

/**
 * @author  王帅涛
 * @date  2021/5/28 19:53
 */

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, MyFile> implements FileService{

    @Resource
    private FileMapper fileMapper;

    //获取保存路径
    @Value("${file.root-path}")
    private String rootPath;

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        //获取日期
        DateTime today = DateTime.now();
        //生成数据库file表对象
        MyFile myFile = new MyFile()
                .setUuid(UUID.fastUUID().toString())
                .setOriginName(file.getOriginalFilename())
                .setSize(Convert.toStr(file.getSize()))
                .setType(file.getContentType())
                .setCreateTime(today);

        //按照日期，生成对应日期文件夹路径
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        //生成路径，拿到文件后缀，如果没有后缀则为空
        String suffix = myFile.getOriginName().substring(myFile.getOriginName().lastIndexOf("."));
        //生成文件全路径
        String path = rootPath+simpleDateFormat.format(today)+"/"+myFile.getUuid()+suffix;
        //上传文件
        File newFile = new File(path);
        //判断文件夹是否存在，若不存在则创建
        if (!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        //获得输出流
        FileOutputStream  fileOutputStream = new FileOutputStream(newFile);
        //拷贝文件
        FileCopyUtils.copy(file.getInputStream(),fileOutputStream);
        //存入数据库表中
        myFile.setPath(path);
        fileMapper.insert(myFile);
        return myFile.getUuid();
    }

    @Override
    public void downloadFile(String fileId, HttpServletResponse response) throws Exception {
        MyFile myFile = fileMapper.selectById(fileId);
        //查看文件是否存在
        File file = new File(myFile.getPath());
        //如果文件不存在返回410
        if (!file.exists()){
            throw new Exception("文件不存在");
        }
        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(myFile.getOriginName(), "UTF-8"));
        //实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fileInputStream =new FileInputStream(file);
        //缓冲输入流
        BufferedInputStream bufferedInputStream =  new BufferedInputStream(fileInputStream);
        //获得响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //读入缓存流
        int i = bufferedInputStream.read(buffer);
        while (i!=-1){
            outputStream.write(buffer,0,i);
            i = bufferedInputStream.read(buffer);
        }
        //关闭缓冲流和文件流
        bufferedInputStream.close();
        fileInputStream.close();
    }
}
